package middleware

import (
	"github.com/gin-gonic/gin"
	"go-admin/server/internal/repository"
	"net/http"
)

type PermissionVerificationMiddlewareBuilder struct {
	repo repository.AdminRepository
}

func NewPermissionVerificationMiddlewareBuilder(repo repository.AdminRepository) *PermissionVerificationMiddlewareBuilder {

	return &PermissionVerificationMiddlewareBuilder{
		repo: repo,
	}
}

func (pv *PermissionVerificationMiddlewareBuilder) Build() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		path := ctx.Request.URL.Path

		if IsPathPublic(path) {
			return
		}

		var isRead int32
		isRead = 2
		if ctx.Request.Method == "GET" {
			isRead = 1
		}
		result := pv.repo.PermissionVerification(ctx, JwtAdmin.AdminID, path, isRead)
		type Result struct {
			Code int    `json:"code"`
			Msg  string `json:"msg"`
		}
		if !result {
			ctx.JSON(http.StatusOK, Result{
				Code: http.StatusPartialContent,
				Msg:  "没有该操作权限",
			})
			ctx.Abort()
			return
		}
		ctx.Next()
	}
}
